﻿using System;
using System.Windows.Forms;
using SdmxMl.GenericMetadata;
using SdmxMl.Manager;
using SdmxMl.Structure;
using SdmxMl.Panels;

namespace SdmxMl.UC
{
    public partial class UcMetadataSetType : UserControl
    {
        protected TreeNode treeNode;
        private MetadataSetType metaSet;
        protected UcMlText ucMlText = null;
        protected bool _isFinal;
        private bool inBinding;
        protected PanelAnnotationList pannelAnnot;


        public UcMetadataSetType()
        {
            InitializeComponent();
            ucMlText = new UcMlText();
            comboBoxTitle.DropDownControl = ucMlText;
        }

        public virtual bool BindFromNode(TreeNode node, PanelAnnotationList pannel, bool isFinal)
        {
            _isFinal = isFinal;
            treeNode = node;
            metaSet = null;
            pannelAnnot = pannel;
            if (node != null)
            {
                metaSet = node.Tag as MetadataSetType;

            }
            BindToControls();

            return Visible;
        }

        private void BindToControls()
        {
            if (metaSet != null)
            {
                inBinding = true;

                // Do we allow editing. 
                IsFinalEditControls(_isFinal);

                numTextBoxSetId.Text = metaSet.Id;
                textBoxVersion.Text = metaSet.Version;
                ucAgencyRef.Text = metaSet.AgencyId;

                numTextBoxNbRows.Text = "0";
                Visible = true;
                comboBoxTitle.Text = metaSet.Name.ToString();
                checkBoxFinal.Checked = metaSet.IsFinal;
                ucMlText.ML = metaSet.Name;
                ucMetadataStructureRef1.BindRef(metaSet);

                ucDatePickerFrom.Date = metaSet.ValidFrom;
                ucDatePickerTo.Date = metaSet.ValidTo;

                textBoxPubPeriod.Text = metaSet.PublicationPeriod;
                numTextBoxPubYear.Text = metaSet.PublicationYear;

                textBoxReportBegin.Text = metaSet.ReportingBeginDate;
                textBoxReportEnd.Text = metaSet.ReportingEndDate;

                inBinding = false;
            }
            else
                Visible = false;
        }
        // Manage Edition possibility
        private void IsFinalEditControls(bool isFinal)
        {
            ucMetadataStructureRef1.IsFinal = isFinal;
            textBoxVersion.ReadOnly = isFinal;
            ucAgencyRef.IsFinal = isFinal;
            numTextBoxSetId.ReadOnly = isFinal;
            numTextBoxNbRows.ReadOnly = isFinal;
            textBoxPubPeriod.ReadOnly = isFinal;
            numTextBoxPubYear.ReadOnly = isFinal;
            textBoxReportBegin.ReadOnly = isFinal;
            textBoxReportEnd.ReadOnly = isFinal;
            comboBoxTitle.IsFinal = isFinal;
            ucDatePickerFrom.IsFinal = isFinal;
            ucDatePickerTo.IsFinal = isFinal;
        }

        public bool UpdateNodeTag(TreeNode node)
        {
            bool err = false;
            if (node != null)
            {
                err = BindFromControls();
                if (metaSet != null && node.Text != metaSet.ToString())
                    node.Text = metaSet.ToString();
            }

            return err; // true on error
        }

        protected bool BindFromControls()
        {
            bool err = false;
            if (metaSet != null)
            {
                metaSet.Id = numTextBoxSetId.Text;
                metaSet.Version = textBoxVersion.Text;
                metaSet.AgencyId = ucAgencyRef.Text;
                metaSet.Name.UpdateForCurrentLanguage(comboBoxTitle.Text);
                metaSet.IsFinal = checkBoxFinal.Checked;
                metaSet.ValidFrom = ucDatePickerFrom.Date;
                metaSet.ValidTo = ucDatePickerTo.Date;

                metaSet.PublicationPeriod = textBoxPubPeriod.Text;
                metaSet.PublicationYear = numTextBoxPubYear.Text;

                metaSet.ReportingBeginDate = textBoxReportBegin.Text;
                metaSet.ReportingEndDate = textBoxReportEnd.Text;

            }
            return err;
        }

        // Creare metadataset rows
        private void butAdd_Click(object sender, EventArgs e)
        {
            // Are references valid ?
         ArtefactList alMetadataStructureDefinitionsList = null;
         MetadataStructureDefinitionType msd = null;
         ReportStructureType r = null;

         alMetadataStructureDefinitionsList = ReferenceManager.GetArtefactList(SdmxArtefactType.MetadataStructureDefinitions);
         msd = ReferenceManager.LocateMetadataStructureDefinition(metaSet.MetadataStructureRef);
         r = ReferenceManager.LocateReportStructure(metaSet.MetadataStructureRef, metaSet.ReportRef);


         if (r != null && msd != null)
         {
             int nb = 0;
             if (numTextBoxNbRows.Text.Length > 0)
                 nb = Convert.ToInt32(numTextBoxNbRows.Text);
             if (nb <= 0)
             {
                 MessageBox.Show("Please specify a valid number of rows!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             else
             {
                 for (int i = 0; i < nb; i++)
                 {
                     AttributeValueSetType at = new AttributeValueSetType(msd, r, metaSet);
                     metaSet.AttributeValueSetList.Add(at);
                     at.FillNode(treeNode);
                 }
                 treeNode.Expand();
             }
         }
         else
             MessageBox.Show("Unknown Metadata Structure Definition!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        #region IsFinal validation control

        protected void checkBoxIsFinal_CheckedChanged(object sender, System.EventArgs e)
        {
            if (inBinding)
                return;
            CheckBox ckb = sender as CheckBox;
            if (ckb != null)
            {
                // change isFinal state for Read only effect
                UpdateNodeTag(treeNode);
                // If checked process a XSD validation of artefact
                if (metaSet.IsFinal)
                {
                  //  ValidateWithXsd();
                }

                pannelAnnot.BindFromNode(treeNode.Tag, ckb.Checked);
                BindFromNode(treeNode, pannelAnnot, ckb.Checked);
            }
        }
        /*
        protected void ValidateWithXsd()
        {
            string strFilename = string.Empty;

            try
            {
                ArtefactManager am = treeNode.Parent.Tag as ArtefactManager;

                strFilename = am.SaveTempArtefact(ar);

                XmlValidator xv = new XmlValidator();
                string err = xv.ValidateSdmxStructure(strFilename, System.EventArgs.Empty);
                if (err.Length > 0)
                {
                    MessageBox.Show("Caution: Artefact validation with XML schema detected some errors!" +
                    System.Environment.NewLine + System.Environment.NewLine + err, "XSD Validation Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }

            catch (Exception ex)
            {
                string s = ex.Message;
            }
            finally
            {
                if (strFilename.Length > 0)
                {
                    try { System.IO.File.Delete(strFilename); }
                    catch { }
                }
            }
        }
         * */
        #endregion

    }
}
